package com.zly.framework.rbac.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zly.framework.rbac.model.entity.Permission;
import com.zly.framework.rbac.model.entity.Role;
import com.zly.framework.rbac.model.entity.SecurityUserDetails;
import com.zly.framework.rbac.model.entity.User;
import com.zly.framework.rbac.exception.SystemException;
import com.zly.framework.rbac.mapper.PermissionMapper;
import com.zly.framework.rbac.mapper.UserMapper;
import com.zly.framework.rbac.service.RoleService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;


@Slf4j
@Component
public class SecurityUserServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleService roleServiceImpl;

    @Resource
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        if (user!=null){
            List<Role> roleList = roleServiceImpl.getAllRolesByUserId(user);
            List<Permission> permissionList = permissionMapper.getAllPermissionsByUserId(user);
            user.setRoles(roleList);
            user.setPermissions(permissionList);
            return new SecurityUserDetails(user);
        }else {
            throw new SystemException("用户名不存在");
        }
    }
}
